package com.imc.platform.base.user.security;

/**
 * Created by tanweiping on 2018/7/20.
 */

import com.imc.platform.base.menu.dao.repository.MenuRepository;
import com.imc.platform.base.menu.pojo.Menu;
import com.imc.platform.base.menu.service.impl.MenuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/*
* 类描述：权限认证
* 开发者：tanweiping
* 创建日期：2018/8/7 10:35
*/
@Service
public class MyInvocationSecurityMetadataSourceService  implements
        FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuRepository menuRepository;

    private HashMap<String, Collection<ConfigAttribute>> map =null;

    /*
    * tanweiping  2018/8/7 10:36
    * 方法描述：加载权限表中所有权限
    */
    public void loadResourceDefine(){
        map = new HashMap<>();
        Collection<ConfigAttribute> array;
        ConfigAttribute cfg;
        List<Menu> permissions = menuRepository.findAll();
        for(Menu permission : permissions) {
            array = new ArrayList<>();
            if (StringUtils.isEmpty(permission.getMenuName())||StringUtils.isEmpty(permission.getMenuUrl())) continue;
            cfg = new SecurityConfig(permission.getMenuName());
            //此处只添加了用户的名字，其实还可以添加更多权限的信息，例如请求方法到ConfigAttribute的集合中去。此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数。
            array.add(cfg);
            //用权限的getUrl() 作为map的key，用ConfigAttribute的集合作为 value，
            map.put(permission.getMenuUrl(), array);
        }

    }

    /*
    * tanweiping  2018/8/7 10:36
    * 方法描述：此方法是为了判定用户请求的url 是否在权限表中，如果在权限表中，则返回给 decide 方法，用来判定用户是否有此权限。如果不在权限表中则放行。
    */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        if(map ==null) loadResourceDefine();
        //object 中包含用户请求的request 信息
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        AntPathRequestMatcher matcher;
        String resUrl;
        for(Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
            resUrl = iter.next();
            matcher = new AntPathRequestMatcher(resUrl);
            if(matcher.matches(request)) {
                return map.get(resUrl);
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
